package cn.cttic.link.dubbo;

import cn.cttic.common.core.exception.user.UserException;
import cn.cttic.link.api.RemoteThirdSmsService;
import cn.cttic.resource.api.domain.RemoteSms;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.api.entity.SmsResponse;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;

@Service
@Slf4j
@RequiredArgsConstructor
@DubboService
public class RemoteThirdSmsServiceImpl implements RemoteThirdSmsService {

    /**
     * 获取特定供应商类型的 SmsBlend 实例
     *
     * @return SmsBlend 实例，代表指定供应商类型
     */
    private SmsBlend getSmsBlend() {
        log.info("短信供应商 {}", SmsFactory.getAll());
        // 可自定义厂商配置获取规则 例如根据租户获取 或 负载均衡多个厂商等
        return SmsFactory.getSmsBlend("config1");
    }

    /**
     * 根据给定的 SmsResponse 对象创建并返回一个 RemoteSms 对象，封装短信发送的响应信息
     *
     * @param smsResponse 短信发送的响应信息
     * @return 封装了短信发送结果的 RemoteSms 对象
     */
    private RemoteSms getRemoteSms(SmsResponse smsResponse) {
        // 创建一个 RemoteSms 对象，封装响应信息
        RemoteSms sms = new RemoteSms();
        sms.setSuccess(smsResponse.isSuccess());
        sms.setResponse(smsResponse.getData().toString());
        sms.setConfigId(smsResponse.getConfigId());
        return sms;
    }

    /**
     * 发送短信验证码
     *
     * @param phone      手机号
     * @param verifyCode
     * @return 结果
     */
    @Override
    public RemoteSms sendSaleCustomerVerifyCode(String phone, String verifyCode) throws UserException {
        log.info("短信供应商 {}", SmsFactory.getAll());
        log.info("短信参数 {}, {}", phone, verifyCode);
        return getRemoteSms(SmsFactory.getSmsBlend().sendMessage(phone, verifyCode));
    }

    /**
     * 发送通知信息
     *
     * @param phone
     * @param user        用户信息
     * @param installCode 安装码
     * @param installUrl  详情地址
     * @return 结果
     */
    @Override
    public RemoteSms sendInstallCustomerNotice(String phone, String user, String installCode, String installUrl) throws UserException {
        LinkedHashMap<String, String> params = new LinkedHashMap<>();
        log.info("短信供应商 {}", SmsFactory.getAll());
        log.info("短信参数 {}, {}, {}, {}", phone, user, installCode, installUrl.substring(29));
        params.put("name", user);
        params.put("trade_name", "交信北斗智能车载");
        params.put("pick_up_code", installCode);
        params.put("code", installUrl.substring(29));
        // name-个人姓名；trade_name-其他（如名称、账号、地址等）；pick_up_code-其他号码；code-链接参数
        return getRemoteSms(SmsFactory.getSmsBlend().sendMessage(phone, "SMS_476940003", params));
    }

//    public static void main(String[] args) {
//        String x = "https://setup.cttic-bd.com/i/B6479B358A";
//        System.out.println(x.substring(29));
//    }
}
